//
//  CZEmotionToolbar.swift
//  表情键盘
//
//  Created by Albert Zhu on 16/10/27.
//  Copyright © 2016年 Albert Zhu. All rights reserved.
//

import UIKit

protocol CZEmotionToolbarDelegate: NSObjectProtocol {
    /// 表情工具栏选中分组项索引
    ///
    /// - parameter toolbar:   toolbar
    /// - parameter itemIndex: 所在分组序号
    func emotionToolbar(_ toolbar: CZEmotionToolbar, didSelected itemIndex: Int)
}

class CZEmotionToolbar: UIView {
    
    weak var delegate: CZEmotionToolbarDelegate?
    
    var selectIndex: Int = 0 {
        didSet {
            for btn in subviews as! [UIButton] {
                btn.isSelected = (btn.tag == selectIndex) ? true : false
            }
        }
    }
    
    override func awakeFromNib() {
        setupUI()
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        let count = subviews.count
        let w = bounds.width / CGFloat(count)
        
        for (i, btn) in subviews.enumerated() {
            btn.frame = CGRect(x: CGFloat(i) * w, y: 0, width: w, height: bounds.height)
        }
    }
    
    @objc func clickItem(button: UIButton) {
        
        if selectIndex == button.tag {return}
        
        selectIndex = button.tag
        
        delegate?.emotionToolbar(self, didSelected: button.tag)
    }
}

private extension CZEmotionToolbar {
    func setupUI() {
    let nameArr = ["最近", "默认", "emoji", "浪小花"]
        
        for (i, str) in nameArr.enumerated() {
            let btn = UIButton(type: .custom)
            btn.setTitle(str, for: [])
            btn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
            
            btn.adjustsImageWhenHighlighted = false
            btn.setTitleColor(UIColor.lightGray, for: [])
            btn.setTitleColor(UIColor.darkGray, for: .selected)
            btn.setBackgroundImage(UIImage(named: "timeline_card_middle_background"), for: [])
            btn.setBackgroundImage(UIImage(named: "timeline_card_middle_background_highlighted"), for: .selected)
            
            btn.sizeToFit()
            btn.tag = i
            
            addSubview(btn)
            
            btn.addTarget(self, action: #selector(clickItem), for: .touchUpInside)
        }
        
        (subviews[0] as! UIButton).isSelected = true
    }
}
